<script lang="ts" setup>
import { ref, reactive, toRefs } from "vue" // vue
import { FormInstance, ElMessageBox, ElMessage } from "element-plus" // elment
import { Search, Refresh } from "@element-plus/icons-vue" // 按钮图标
import Editor from "@/components/RichText/index.vue" // 引入富文本
import { createDataApi, putDataApi, delDataApi, getDataOneApi } from "@/api/repository/postRepository" // 接口
import { useUserStore } from "@/store/modules/user" // 获取用户信息
import { getclassificationDataApi } from "@/api/repository/classificationRepository" // 接口
const userStore = useUserStore() // 获取用户信息
// const { paginationData, handleCurrentChange, handleSizeChange } = usePagination() // 分页器

// 表单
const data = reactive<any>({
  formData: {
    details: "",
    type: "comprehensive"
  },
  tableData: {},
  searchData: {
    title: undefined,
    type: "comprehensive"
  }, // 表单验证
  rules: {
    title: [
      {
        required: true,
        message: "请输入标题",
        trigger: "blur"
      }
    ]
  }
})
const { searchData, formData, rules, tableData } = toRefs(data)
// #region 查分类
const tableDataFl = ref<any>([])
const activeNames = ref<any>([])
function tablelistFl() {
  getclassificationDataApi(searchData.value)
    .then((res: any) => {
      tableDataFl.value = res.data
      // 拿到每个分类id添加到数组全部展开
      res.data.forEach((element: any) => {
        activeNames.value.push(element.id)
      })
      // console.log(tableData.value)
      // console.log(tableDataSubs.value)
    })
    .catch(() => {
      tableDataFl.value = []
    })
}
tablelistFl()
// #endregion

// #region 搜索内容
const searchFormRef = ref<FormInstance | null>(null)
// 搜索
function handleSearch() {
  tablelistFl()
  console.log(tableDataFl.value[0].knowledgeBases[0], 7)
  // gocdDiv(tableDataFl.value[0].knowledgeBases[0])
}
// 重置
function resetSearch() {
  searchFormRef.value?.resetFields()
  handleSearch()
  tableData.value = {}
}

// #endregion

// #region 页面展开与收起
// const expand = ref()
// function goUpDown(e: any) {
//   if (expand.value == e) {
//     expand.value = undefined
//   } else {
//     expand.value = e
//   }
// }
// 控制展开样式
// function expandclass(index: any) {
//   return expand.value == index ? "expandBox2" : "expandBox"
// }
// 小菜单样式

const cdDiv = ref()
function cdDivClick(index: any) {
  return cdDiv.value == index ? "cdDivclass" : "cdDivclassTwo"
}

function gocdDiv(e: any) {
  getDataOneApi({ id: e.id }).then((res: any) => {
    console.log(res)
    tableData.value = res.data
  })
  if (cdDiv.value == e) {
    cdDiv.value = undefined
  } else {
    cdDiv.value = e
  }
}
// #endregion

// #region 添加和修改框
const dialogVisible = ref(false)
const formRef = ref<FormInstance | null>(null)
const ids = ref(undefined) // 判断修改还是增加

// 富文本
const getMsg = (val: any) => {
  if (val) {
    formData.value.details = val
  }
  console.log(val, "富文本")
}

// 修改
const handleUpdate = (row: any) => {
  ids.value = row.id
  dialogVisible.value = true
  formData.value = JSON.parse(JSON.stringify(row)) // 赋值需要深拷贝
}

// 删除
const handleDelete = (row: any) => {
  ElMessageBox.confirm(`您确定要删除吗?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    delDataApi({ id: row.id }).then(() => {
      ElMessage.success("删除成功")
      tablelistFl()
      tableData.value = {}
    })
  })
}

// 清空form框
const clearValidate = () => {
  formRef.value?.resetFields()
}

// 清空对话框
const resetForm = () => {
  ids.value = undefined
  clearValidate()
  formData.value = {}
  formData.value.details = "<p><br></p>"
  formData.value.type = "comprehensive"
}

// 确定按钮
const handleCreate = () => {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      if (ids.value === undefined) {
        createDataApi(formData.value).then(() => {
          ElMessage.success("新增成功")
          dialogVisible.value = false
          tablelistFl()
          tableData.value = {}
        })
      } else {
        putDataApi(formData.value).then(() => {
          ElMessage.success("修改成功")
          dialogVisible.value = false
          tablelistFl()
          tableData.value = {}
        })
      }
    } else {
      return false
    }
  })
}
// #endregion

/** 监听分页参数的变化 */
// watch([() => paginationData.currentPage, () => paginationData.pageSize], tablelist, { immediate: true })
</script>

<template>
  <div class="app-container">
    <el-card>
      <el-row justify="center" align="middle">
        <el-col :span="12">
          <el-form ref="searchFormRef" :inline="true" :model="searchData">
            <el-form-item prop="title">
              <el-input
                v-model.trim="searchData.title"
                clearable
                placeholder="搜索综合知识库相关标题"
                style="width: 500px"
              >
                <template #append
                  ><el-button
                    style="background-color: #419eff; color: #fff; display: flex"
                    :icon="Search"
                    @click="handleSearch"
                    >查询</el-button
                  >
                </template>
              </el-input>
            </el-form-item>
            <el-form-item>
              <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
              <el-button
                v-if="
                  userStore.roles.join() == '超级管理员' ||
                  userStore.roles.join() == '质检部客服组' ||
                  userStore.roles.join() == '子账户超级管理员' ||
                  userStore.roles.join() == '渠道部子账户管理员'
                "
                @click="dialogVisible = true"
                >新增综合知识</el-button
              >
            </el-form-item>
          </el-form></el-col
        >
      </el-row>
    </el-card>
    <div style="display: flex; margin-top: 20px; justify-content: space-between">
      <!-- 菜单 -->
      <el-card style="width: 15%">
        <el-scrollbar height="600px">
          <div>
            <el-collapse v-model="activeNames">
              <el-collapse-item
                class="title-large"
                v-for="(item, index) in tableDataFl"
                :key="index"
                :title="item.name"
                :name="item.id"
              >
                <div v-for="(i, d) in item.knowledgeBases" :key="d" :class="cdDivClick(i)" @click="gocdDiv(i)">
                  <div>{{ i.title }}</div>
                </div>
              </el-collapse-item>
            </el-collapse>
          </div>
        </el-scrollbar>
      </el-card>
      <!-- 内容 -->
      <el-card v-if="JSON.stringify(tableData) == '{}'" class="zwclass"><div>请选择相关标题...</div></el-card>
      <el-card v-else style="width: 82%">
        <el-scrollbar height="600px">
          <div>
            <p style="font-size: 22px; color: #333">标题：{{ tableData.title }}</p>
            <el-divider />
            <div>
              <div class="ql-editor" v-html="tableData.details" />
            </div>

            <div class="footbox">
              <div>
                <el-button
                  v-if="
                    userStore.roles.join() == '超级管理员' ||
                    userStore.roles.join() == '质检部客服组' ||
                    userStore.roles.join() == '子账户超级管理员' ||
                    userStore.roles.join() == '渠道部子账户管理员'
                  "
                  @click="handleUpdate(tableData)"
                  type="primary"
                  link
                >
                  修改
                </el-button>
                <el-button
                  v-if="
                    userStore.roles.join() == '超级管理员' ||
                    userStore.roles.join() == '质检部客服组' ||
                    userStore.roles.join() == '子账户超级管理员' ||
                    userStore.roles.join() == '渠道部子账户管理员'
                  "
                  @click="handleDelete(tableData)"
                  type="primary"
                  link
                >
                  删除
                </el-button>
              </div>
            </div>
          </div>
        </el-scrollbar>
      </el-card>
    </div>
    <el-dialog v-model="dialogVisible" @closed="resetForm" width="60%">
      <el-form ref="formRef" :model="formData" label-width="100px" label-position="left" :rules="rules">
        <el-form-item label="分类">
          <el-select v-model="formData.classificationId" filterable clearable style="width: 240px">
            <el-option v-for="item in tableDataFl" :key="item.id" :label="item.name" :value="item.id"
          /></el-select>
        </el-form-item>
        <el-form-item prop="title" label="标题">
          <el-input v-model="formData.title" placeholder="请输入综合知识" />
        </el-form-item>
        <el-form-item prop="details" label="详情">
          <Editor :value="formData.details" @updateValue="getMsg" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleCreate">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.expandBox {
  max-height: 80px;
  min-height: 80px;
  overflow: hidden;
  transition: max-height ease-in-out 0.2s;
}
.expandBox2 {
  min-height: 80px;
  overflow: hidden;
  transition: max-height ease-in-out 0.2s;
}
.footbox {
  margin-top: 20px;
  display: flex;
  justify-content: space-between;
}
.pagination {
  display: flex;
  justify-content: flex-end;
}
.spans {
  margin-left: 20px;
}
// 点击之后文字不居中
.cdDivclass {
  display: flex;
  align-items: center;
  color: #589efe;
  background-color: #ecf1fa;
  padding: 2px;
  font-size: 16px;
}
.cdDivclassTwo {
  display: flex;
  align-items: center;
  padding: 2px;
  font-size: 16px;
}
.zwclass {
  width: 82%;
  display: flex;
  justify-content: center;
  align-items: center;
}
::v-deep(.el-collapse-item__header) {
  font-size: 16px;
  line-height: 16px;
  font-weight: 700;
}
</style>
